<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores/index.js'
import { userUpdateAvatarService } from '@/api/user.js'

defineOptions({
  name: 'UserAvatar'
})

// 基于 store 初始化 imageUrl
const userStore = useUserStore()
const imageUrl = ref(userStore.userInfo.user_pic)
const uploadRef = ref()
const isLoading = ref(false)

// 预览图片
const onSelectFile = (file) => {
  // 基于 FileReader 生成图片预览
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = function () {
    imageUrl.value = reader.result
  }
}

// 更换头像
const onUpdateAvatar = async () => {
  isLoading.value = true
  await userUpdateAvatarService(imageUrl.value)
  await userStore.getUserInfo()
  isLoading.value = false
  ElMessage.success('头像更换成功！')
}
</script>

<template>
  <PageContainer title="更换头像">
    <el-upload
      class="avatar-uploader"
      :auto-upload="false"
      :show-file-list="false"
      ref="uploadRef"
      :on-change="onSelectFile"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="图片" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <br />
    <el-button
      plain
      type="primary"
      :icon="Plus"
      size="large"
      @click="uploadRef.$el.querySelector('input').click()"
      >选择图片</el-button
    >
    <el-button
      plain
      type="success"
      :icon="Upload"
      size="large"
      @click="onUpdateAvatar"
      :loading="isLoading"
      >上传图片</el-button
    >
  </PageContainer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 300px;
      height: 300px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 300px;
      text-align: center;
    }
  }
}
</style>
